<template>
  <view class="profile-page">
    <!-- 顶部信息卡片 -->
    <view class="profile-header">
      <view class="avatar-section">
        <view class="avatar-wrapper" @click="chooseAvatar">
          <up-avatar
            v-if="!userInfo.avatar"
            :text="
              userInfo.nickname ? userInfo.nickname.substring(0, 1) : 'DCS-1'
            "
            size="70"
            bgColor="#2979ff"
          ></up-avatar>
          <up-avatar
            v-else
            :src="userInfo.avatar || ''"
            size="70"
            bgColor="#2979ff"
          ></up-avatar>
          <view class="avatar-edit">
            <up-icon name="camera" size="16" color="#ffffff"></up-icon>
          </view>
        </view>
        <text class="avatar-tip">点击更换头像</text>
      </view>
    </view>

    <!-- 个人信息表单 -->
    <view class="profile-form">
      <up-form
        :model="userInfo"
        :rules="formRules"
        ref="profileFormRef"
        labelPosition="left"
        labelWidth="80"
      >
        <view class="form-card">
          <view class="form-header">
            <text class="form-title">基本信息</text>
          </view>

          <up-form-item label="昵称" prop="nickname" :borderBottom="true">
            <up-input
              v-model="userInfo.nickname"
              placeholder="请输入昵称"
              border="none"
            ></up-input>
          </up-form-item>

          <up-form-item
            label="性别"
            prop="gender"
            :borderBottom="true"
            @click="showGenderPicker = true"
          >
            <up-input
              v-model="genderText"
              placeholder="请选择性别"
              disabled
              disabledColor="#ffffff"
              border="none"
            ></up-input>
            <template #right>
              <up-icon name="arrow-right" size="16" color="#c0c4cc"></up-icon>
            </template>
          </up-form-item>
        </view>

        <view class="form-card">
          <view class="form-header">
            <text class="form-title">联系方式</text>
          </view>

          <up-form-item label="手机号" prop="phone" :borderBottom="true">
            <up-input
              v-model="userInfo.phone"
              placeholder="请输入手机号"
              type="number"
              maxlength="11"
              border="none"
            ></up-input>
          </up-form-item>

          <up-form-item label="邮箱" prop="email" :borderBottom="false">
            <up-input
              v-model="userInfo.email"
              placeholder="请输入邮箱"
              border="none"
            ></up-input>
          </up-form-item>
        </view>
      </up-form>
    </view>

    <!-- 保存按钮 -->
    <view class="save-section">
      <up-button type="primary" @click="saveProfile">保存</up-button>
    </view>

    <!-- 性别选择器 -->
    <up-action-sheet
      :show="showGenderPicker"
      :actions="genderOptions"
      title="请选择性别"
      @close="showGenderPicker = false"
      @select="selectGender"
    ></up-action-sheet>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { getUserInfo } from "@/api/user";
import { uploadFile } from "@/api/common";
import { updateUserInfo } from "@/api/user";
import { useUserStore } from "@/stores/user";

const userStore = useUserStore();

// 用户信息
const userInfo = reactive({
  avatar: "",
  nickname: "",
  email: "",
  gender: 1,
  phone: "",
});

// 表单验证规则
const formRules = {
  nickname: [{ required: true, message: "请输入昵称", trigger: "blur" }],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
  email: [
    {
      pattern: /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/,
      message: "请输入正确的邮箱地址",
      trigger: "blur",
    },
  ],
};

// 表单引用
const profileFormRef = ref(null);

// 性别选择器
const showGenderPicker = ref(false);
const genderOptions = [
  { name: "保密", value: 0 },
  { name: "男", value: 1 },
  { name: "女", value: 2 },
];

// 计算属性
// 性别文本
const genderText = computed(() => {
  const gender = userInfo.gender;
  if (gender === 1) return "男";
  if (gender === 2) return "女";
  return "";
});

// 生命周期钩子
onMounted(() => {
  getUserProfile();
});

// 获取用户信息
async function getUserProfile() {
  try {
    // 从本地存储获取用户信息
    const res = await getUserInfo();
    if (res.success) {
      const savedUserInfo = res.data;
      // 合并保存的用户信息到当前用户信息
      Object.keys(userInfo).forEach((key) => {
        if (savedUserInfo[key] !== undefined) {
          userInfo[key] = savedUserInfo[key];
        }
      });
    }
  } catch (error) {
    console.error("获取用户信息失败:", error);
  }
}

// 选择头像
function chooseAvatar() {
  uni.chooseImage({
    count: 1,
    sizeType: ["compressed"],
    sourceType: ["album", "camera"],
    success: async (res) => {
      userInfo.avatar = res.tempFilePaths[0];
      console.log("选择头像成功:", userInfo.avatar); // 打印上传的图片信息
      // 上传图片
      const response = await uploadFile(userInfo.avatar);
      console.log("上传图片成功:", response);
      if (response) {
        userInfo.avatar = response;
        uni.showToast({
          title: "头像已更新",
          icon: "success",
        });
      } else {
        uni.showToast({
          title: "头像更新失败",
          icon: "error",
        });
      }
    },
  });
}

// 选择性别
function selectGender(item) {
  userInfo.gender = item.value;
  showGenderPicker.value = false;
}

// 选择部门
function selectDepartment(item) {
  userInfo.departmentId = item.value;
  showDepartmentPicker.value = false;
}

// 选择日期
function selectDate(e) {
  userInfo.joinDate = e.fulldate;
  showDatePicker.value = false;
}

async function saveProfile() {
  if (!profileFormRef.value) return;

  try {
    await profileFormRef.value.validate();
  } catch (error) {
    console.error("表单校验失败:", error);
    uni.showToast({
      title: "表单校验失败",
      icon: "error",
    });
    return; // 校验失败时直接返回
  }

  uni.showLoading({
    title: "保存中...",
  });

  try {
    const res = await updateUserInfo(userInfo);
    if (res.success) {
      const response = await getUserInfo();
      const permissions = response.data.userRoleList.map(
        (item) => item.roleName
      );
      userStore.setUserInfo({
        username: response.username,
        nickname: response.nickname,
        permissions: permissions,
      });
      uni.hideLoading(); // 成功时关闭
      uni.showToast({
        title: "保存成功",
        icon: "success",
      });
      setTimeout(() => uni.navigateBack(), 1500);
    } else {
      uni.hideLoading(); // 失败时也关闭
      uni.showToast({
        title: "更新失败",
        icon: "none",
      });
    }
  } catch (err) {
    console.error("更新失败:", err);
    uni.hideLoading(); // 异常时也关闭
    uni.showToast({
      title: "请求异常",
      icon: "none",
    });
  }
}
</script>

<style lang="scss" scoped>
.profile-page {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 40px;
}

/* 头像区域 */
.profile-header {
  background-color: #ffffff;
  padding: 30px 0;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  display: flex;
  flex-direction: column;
  align-items: center;
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.avatar-wrapper {
  position: relative;
  margin-bottom: 8px;
}

.avatar-edit {
  position: absolute;
  right: 0;
  bottom: 0;
  width: 24px;
  height: 24px;
  background-color: #2979ff;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 2px solid #ffffff;
}

.avatar-tip {
  font-size: 12px;
  color: #909399;
}

/* 表单区域 */
.profile-form {
  padding: 0 12px;
}

.form-card {
  background-color: #ffffff;
  border-radius: 8px;
  margin-bottom: 16px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.form-header {
  padding: 12px 16px;
  border-bottom: 1px solid #f2f2f2;
}

.form-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

/* 保存按钮 */
.save-section {
  padding: 20px 12px;
}

/* 响应式适配 */
@media screen and (max-width: 500px) {
  .profile-form {
    padding: 0 8px;
  }

  .form-header {
    padding: 10px 12px;
  }

  .form-title {
    font-size: 15px;
  }
}
</style>
